package cn.j2ee.chapter2.web.model.validator;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import cn.j2ee.chapter2.web.model.DataBinderTestModel;

/**
 * 
 * 2016年11月5日 下午4:14:48
 */
public class DataBinderTestModelValidator implements  Validator{
	
	private static final Pattern PASSWORD_PATTERN = Pattern.compile("[a-zA-Z0-9]{5,20}");
	private static final Pattern USERNAME_PATTERN = Pattern.compile("[a-zA-Z]\\w{4,19}");
	private static final Set<String> FORBINDDDEN_WORD_SET = new HashSet<String>();  
    static {  
       FORBINDDDEN_WORD_SET.add("fuck"); 
       FORBINDDDEN_WORD_SET.add("admin");  
    } 
	@Override
	public boolean supports(Class<?> arg0) {
		return DataBinderTestModel.class.equals(arg0);
	}

	@Override
	public void validate(Object object, Errors errors) {
//		 ValidationUtils.rejectIfEmpty(errors, "username", "username.not.empty");
	        DataBinderTestModel dataBinderTestModel = (DataBinderTestModel) object;
	        if(!(USERNAME_PATTERN.matcher(dataBinderTestModel.getUsername()).matches())){
	            errors.rejectValue("username", "username.not.illegal");//如果用户名不合法  
	        }
	        for(String forbiddenWord : FORBINDDDEN_WORD_SET) { 
	        	if(dataBinderTestModel.getUsername().contains(forbiddenWord)) {  
	        		errors.rejectValue("username", "username.forbidden", new Object[]{forbiddenWord}, "您的用户名包含非法关键词");//用户名包含屏蔽关键字  
	                break;  
	        	}
	        }
	        if(!PASSWORD_PATTERN.matcher(dataBinderTestModel.getUsername()).matches()) {  
	            errors.rejectValue("password","password.not.illegal", "密码不合法");//密码不合法  
	        }    
	}

}
